package com.cms.common;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.springframework.beans.factory.annotation.Value;
 

public class LotteryDataSocket {

	@Value("${manual.drawing.addr}")
	private String addr;

	@Value("${manual.drawing.port}")
	private int port;

	/***
	 * @desc 发送socket消息
	 * 
	 */
	public void sendLotteryDataSocket(int lotteryId, String lotteryNo) throws Exception {
		// 创建客户端连接器.
		NioSocketConnector connector = new NioSocketConnector();

		// 设置日志记录器
		connector.getFilterChain().addLast("logger", new LoggingFilter());

		// 设置编码过滤器
		connector.getFilterChain().addLast("codec",
				new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));

		// 设置连接超时检查时间
		connector.setConnectTimeoutCheckInterval(30);

		// 设置事件处理器
		connector.setHandler(new IoHandlerAdapter());

		// 建立连接
		ConnectFuture cf = connector.connect(new InetSocketAddress(addr, port));

		// 等待连接创建完成
		cf.awaitUninterruptibly();

		StringBuilder sb = new StringBuilder();
		sb.append(lotteryId);
		sb.append(",");
		sb.append(lotteryNo);
		sb.append(",manager");

		// 发送消息
		cf.getSession().write(sb.toString());

		// 发送消息
		cf.getSession().write("quit");

		// 等待连接断开
		cf.getSession().getCloseFuture().awaitUninterruptibly();

		// 释放连接
		connector.dispose();

	}
}
